package com.example.dollarShipping.controller.Profile;


import com.example.dollarShipping.entity.Menu;
import com.example.dollarShipping.entity.User;
import com.example.dollarShipping.security.UserDetailsImpl;
import com.example.dollarShipping.service.MenuService;
import com.example.dollarShipping.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/profile")
public class ProfileController {

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;
    @Resource
    PasswordEncoder encoder;

    @ModelAttribute("user")
    public User userDto() {
        //读取当前登录成功用户的角色，并根据角色加载菜单
        //获得spring security用户
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        User u = userService.getDetail(userDetails.getId());
        return u;
    }
    @ModelAttribute("menuList")
    public List<Menu> backGround() {
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        List<Menu>  menu= menuService.getMenu(userDetails.getRoleId());
        return menu;
    }


    @RequestMapping
    public String showProfileForm() {
        System.out.println("myProfile");
        return "profile/userInfo";
    }

    @RequestMapping("/update")
    public String update() {
        System.out.println("myProfile");
        return "profile/userUpdate";
    }


    @PostMapping("/updateInfo")
    public String updateInfo(@ModelAttribute("user") @Valid User user,
                                      BindingResult result){
        userService.updateUserInfo(user);
        return "profile/userInfo";
    }


}
